package com.itheima.dao.impl;

import com.itheima.dao.BaseUserDao;
import com.itheima.domain.Pow;
import com.itheima.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class UserDao implements BaseUserDao {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserDao.class);
    private static ArrayList<User> list = new ArrayList<>();
    static {
        reLoad();
        System.out.println("========== loading ==========");
    }
    @Override
    public boolean addUser(User user) {
        if (getIndex(user.getUsername()) == -1){
            list.add(user);
            reSave();
            return true;
        }
        return false;
    }

    @Override
    public List<User> findAllUser() {
        return list;
    }

    @Override
    public boolean deleteUser(String delId, Pow pow) {
        //判断对象是否存在
        int index = getIndex(delId);
        if (index == -1){
            LOGGER.info(delId + "用户不存在");
            return false;
        }
        //判断权限是否满足
        LOGGER.info(pow + "to delect " + index);
        if (list.get(index).getPow().compareTo(pow) > 0){
            list.remove(index);
            reSave();
            return true;
        }
        return false;
    }

    @Override
    public boolean updateUser(String updateId, User newUser) {
        //判断对象是否存在
        int index = getIndex(updateId);
        if (index == -1){
            return false;
        }
        list.set(index,newUser);
        reSave();
        return true;
    }

    @Override
    public int getIndex(String id) {
        int index = -1;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getUsername().equals(id)) {
                return i;
            }
        }
        return -1;
    }

    public User getUser(String uname){
        int index = getIndex(uname);
        if (index == -1){
            return null;
        }else
            return list.get(index);
    }

    //封装一个方法将数据加载进内存
    private static ArrayList<User> reLoad(){
        //创建反序列化流
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("E:\\testprojects\\StudentManger\\server\\user.txt")));
            list = (ArrayList<User>) ois.readObject();
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            LOGGER.error("反序列化流时,出现异常:" + e.getMessage());
        }
        return null;
    }


    //封装一个方法将数据永久化保存
    private void reSave(){
        try {
            //创建序列化流
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("E:\\testprojects\\StudentManger\\server\\user.txt")));
            oos.writeObject(list);
            oos.close();
        } catch (IOException e) {
            LOGGER.error("序列化流时,出现异常:" + e.getMessage());
        }
    }
}
